<?php
class indexActions extends sfActions {

    public function executeIndex(sfWebRequest $request){
        $this->productTypeList = ProductTypeTable::getProductTypeListOrderByName();
    }

    public function executeLoadItems(sfWebRequest $request){
        $pres = $_POST['pres'];
        $cate = $_POST['cate'];
        $type = $_POST['type'];
        $each = $_POST['each'];
        $term = (string)$_POST['term'];

        $cateArr = array();
        $cateObj = CategoryTable::getCategoryListOrderByName();
    
        $this->_getCategoryIdRecursive($cateObj, $cate, $cateArr);

        sort($cateArr);
        if ($cateArr[0] == 0){
            array_shift($cateArr);
        }
        sort($cateArr);

        $itemArray = ProductTable::getProductList($cateArr, $type);

        if($term != ''){
            $tempArr = $itemArray;
            $itemArray = array();
            $term = '/'.$term.'/i';
            foreach ($tempArr as $item){
                if ($isSearch = preg_match($term, $item['pname'])){
                    $itemArray[] = $item;
                }
            }
        }

        if(count($itemArray) > 0) {
            $itemAmount = count($itemArray);
            $itemsHtml = '';
            $counter = 1;
            $fromNo = $each * ($pres - 1);
            $toNo = $fromNo + $each;
            foreach($itemArray as $item) {
                if($counter > $toNo)
                    break;
                if(($counter > $fromNo) && ($counter <= $toNo)) {
                    $itemsHtml .= self::_itemRender($item['pid'], $item['pname'], $item['thumbnail']);
                }
                $counter++;
            }
            $aryResult['naviHtml'] = self::_prepareNavibar($pres, ceil($itemAmount / $each));
        } else {
            $itemsHtml = '<span style="font-size:14px;">No items in here. Please choose another Category from the left menu, or another File Type.</span>';
            $aryResult['naviHtml'] = '';
        }
        $aryResult['itemsHtml'] = $itemsHtml;
        $aryResult['downloadLink'] = $this->_renderDownloadType($type);

        $breadcrumb = '<a title="Back to Home" onclick="initFilter();refreshCategory();">Home</a>';
        if($cate != 0){
            $cateObj = CategoryTable::getOneById($cate);
            $breadcrumb .= $this->_breadcrumbParentCategoryRender($cateObj->getParentId());
            $breadcrumb .= '<span class="sept">&gt;</span>'.$cateObj->getName();
        }
        $breadcrumb .= ' - '.ProductTypeTable::getNameById($type);
        $aryResult['breadcrumb'] = $breadcrumb;
        
        echo json_encode($aryResult);
        exit();
    }

    public function executeLoadCategory(sfWebRequest $request){
        $cate = $request->getParameter('cate');
        $aryResult['categoryHtml'] = self::_prepareCategory($cate);
        echo json_encode($aryResult);
        exit;
    }

    public function executeDownload(sfWebRequest $request){
        $this->_removeExpiredFile(60*60*3);
        $type = $request->getGetParameter('type');
        $product = $request->getGetParameter('product');
        $typeArr = explode('-', $type);
        $productArr = explode('-', $product);

        $fileList = DownloadLinkTable::getFileListByPidAndTid($productArr, $typeArr);
        if (count($fileList) > 0){
            $fileName = 'tempArchive/'.time().'-'.rand('1000','9999').'.zip';
            $zip = new ZipArchive();
            $zip->open($fileName, ZipArchive::CREATE);
            foreach ($fileList as $item){
                $zip->addFile($item);
            }
            $zip->close();

            header('Content-type: application/force-download');
            header('Content-Disposition: attachment; filename=download.zip');
            header('Pragma: no-cache');
            header('Expiries: 0');
            readfile($fileName);
            exit;
        }
    }

    protected function _prepareCategory($categoryId){
        $categoryArr = CategoryTable::getAll();
        if($categoryId == 0 || $categoryId == null) {
            $tempHtml = '';
            foreach($categoryArr as $item) {
                if($item->getParentId() == 0) {
                    $tempHtml .= '<li><a onclick="checkCategory(' . $item->getId() . ')" title="' . $item->getName() .
                     '">' . $item->getName() . '</a></li>';
                }
            }
        } else {
            $tempHtml = '<li><a onclick="checkCategory(0)"  title="Back to All Categories">Back to All Categories</a><ul>';
            $childHtml = '';
            foreach($categoryArr as $item) {
                if($item->getParentId() == $categoryId) {
                    $childHtml .= '<li><a onclick="checkCategory(' . $item->getId() . ')" title="' . $item->getName() .
                     '">' . $item->getName() . '</a></li>';
                }
            }
            $tempHtml .= $this->_recursiveCateWrap($categoryArr, $categoryId, $childHtml);
            $tempHtml .= '</ul></li>';
        }
        return $tempHtml;
    }

    protected function _recursiveCateWrap($categoryArr, $wrapId, $childHtml){
        foreach ($categoryArr as $item){
            if ($item->getId() == $wrapId){
                $currentCate = $item;
                break;
            }
        }
        if (!isset($currentCate)){
            return false;
        }
        $tempHtml = '<li><a class="selected" onclick="checkCategory('.$currentCate->getId().')" title="'.$item->getName().'">'.$item->getName().'</a><ul>';
        $tempHtml .= $childHtml.'</ul></li>';
        if($currentCate->getParentId() == 0 || $currentCate->getParentId() == 'null'){
            return $tempHtml;
        } else {
            return $this->_recursiveCateWrap($categoryArr, $currentCate->getParentId(), $tempHtml);
        }
    } 

    protected function _prepareNavibar($presentPage, $maxPage = 100){
        $navibarHtml = '<span class="pages">Page:</span>';
        $presentPage = (int)$presentPage;
        $maxPage = (int)$maxPage;
        //prev button
        if($presentPage > 1) {
            $navibarHtml .= '<a onclick="naviTo(' . ($presentPage - 1) . ')">&lt;&lt; Prev</a>';
        }
        //first page when far away from this page
        if(($presentPage - 3) > 1) {
            $navibarHtml .= '<a onclick="naviTo(1)">1</a>';
        }
        // the '...'
        if(($presentPage - 4) > 1) {
            $navibarHtml .= '<span>...</span>';
        }
        //three before present
        for($i = ($presentPage - 3); $i < $presentPage; $i++) {
            if($i >= 1) {
                $navibarHtml .= '<a onclick="naviTo(' . $i . ')">' . $i . '</a>';
            }
        }
        //present page
        $navibarHtml .= '<span class="current">' . $presentPage . '</span>';
        //three after present
        for($i = ($presentPage + 1); $i <= ($presentPage + 3); $i++) {
            if($i <= $maxPage) {
                $navibarHtml .= '<a onclick="naviTo(' . $i . ')">' . $i . '</a>';
            }
        }
        //the '...'
        if(($presentPage + 4) < $maxPage) {
            $navibarHtml .= '<span>...</span>';
        }
        //last page
        if(($presentPage + 3) < $maxPage) {
            $navibarHtml .= '<a onclick="naviTo(' . $maxPage . ')">' . $maxPage . '</a>';
        }
        if($presentPage < $maxPage) {
            $navibarHtml .= '<a onclick="naviTo(' . ($presentPage + 1) . ')">Next &gt;&gt;</a>';
        }
        return $navibarHtml;
    }

    protected function _itemRender($itemId, $itemAlt, $itemImg){
        $tempHtml = '<li><div class="block">' . '<a href="#download_content" class="inline download_img" onclick="productDownload('.$itemId.')">' . '<img src="' .
         $itemImg . '" alt="' . $itemAlt . '" />' . '</a>' . '<input type="checkbox" pid="' . $itemId .
         '" name="check_list" />' . '<a href="#download_content" class="inline" onclick="productDownload('.$itemId.')">' . $itemAlt . '</a>' . '</div></li>';
        return $tempHtml;
    }

    protected function _getCategoryIdRecursive($obj, $pid, &$arr){
        $tempArr = array();
        foreach ($obj as $item){
            $tempId = ($item->getParentId() == null) ? 0 : $item->getParentId();
            if ($tempId == $pid) {
                $tempArr[] = $item->getId();
            }
        }
        if (count($tempArr) > 0) {
            foreach ($tempArr as $item){
                $this->_getCategoryIdRecursive($obj, $item, $arr);
            }
        }
        $arr[] = $pid;
    }

    protected function _renderDownloadType($typeId){
        $tempArr = ProductTypeHasDownloadTypeTable::getDownloadTypesByProductTypeId($typeId);
        $tempHtml = '';
        foreach ($tempArr as $item){
            if ($item->getDownloadTypeId() != 14){
            $tempHtml .= '<span><input type="checkbox" '.
                        'tid="'.$item->getDownloadTypeId().'" name="download_list" />'.
                        $item->getDownloadType()->getName().'</span>';
            }
        }
        $tempHtml .= '<span class="download_btn" id="download-btn"><a onclick="downloadGroup(0)">Download</a></span>';
        return $tempHtml;
    }

    protected function _removeExpiredFile($expiredTime){
        $fileInDir = scandir('tempArchive/');
        $fTime = time()-$expiredTime;
        foreach ($fileInDir as $item){
            if (preg_match('/\.zip$/', $item)){
                $fileTime = substr($item,0,strlen($item)-9);
                if($fileTime < $fTime){
                    unlink('tempArchive/'.$item);
                }
            }
        }
    }
    
    protected function _breadcrumbParentCategoryRender($pid,$html=''){
        if($pid == 0 || $pid == null){
            return $html;
        }else{
            $cateObj = CategoryTable::getOneById($pid);
            $tempHtml = '<span class="sept">&gt;</span>'.
                        '<a title="'.$cateObj->getName().
                        '" onclick="checkCategory('.$cateObj->getId().
                        ')">'.$cateObj->getName().'</a>'.$html;
            return $this->_breadcrumbParentCategoryRender($cateObj->getParentId(), $tempHtml);
        }
    }
}